package com.example.administrator.imageselected;

import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @InjectView(R.id.select_iv_idcardposition)
    ImageView selectIvIdcardposition;
    @InjectView(R.id.select_arrmedphoto)
    ImageView selectArrmedphoto;
    @InjectView(R.id.select_iv_idcardback)
    ImageView selectIvIdcardback;
    @InjectView(R.id.home_call_police)
    ImageView homeCallPolice;
    @InjectView(R.id.select_iv_carinfo)
    ImageView selectIvCarinfo;
    @InjectView(R.id.home_insurance)
    ImageView homeInsurance;
    @InjectView(R.id.bottom)
    Button button;
    private ArrayList<File> images;
    private static final int REQUEST_CAMERA = 1;
    private static final int REQUEST_ALBUM_OK = 2;
    private static final String TAG = "123";

    private File mTmpFile;
    private Button buttonFront;
    private Button buttonBack;
    public ArrayList<ImageView> imageViews = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.carinfo_activity);
        ButterKnife.inject(this);
        initImageLists();
        images = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            File file = new File("1");
            images.add(i, file);
        }
    }


    private void initImageLists() {
        imageViews.add(selectIvIdcardposition);
        imageViews.add(selectIvIdcardback);
        imageViews.add(selectIvCarinfo);
        imageViews.add(selectArrmedphoto);
        imageViews.add(homeCallPolice);
        imageViews.add(homeInsurance);

    }

    public void showCamera() {
        // 跳转到系统照相机
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (cameraIntent.resolveActivity(getPackageManager()) != null) {
            // 设置系统相机拍照后的输出路径
            // 创建临时文件
            mTmpFile = OtherUtils.createFile(getApplicationContext());
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile));
            startActivityForResult(cameraIntent, REQUEST_CAMERA);
        } else {
            Toast.makeText(getApplicationContext(), "成功", Toast.LENGTH_SHORT).show();

        }

    }

    public void showCaptrue() {
        Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(albumIntent, REQUEST_ALBUM_OK);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CAMERA:
                //相机返回结果
                if (mTmpFile.length() > 0) {
                    Log.d(TAG, "onActivityResult: 请求相机： " + mTmpFile.getAbsolutePath());
                    // Bitmap bitmap = BitmapFactory.decodeFile(String.valueOf(mTmpFile));
                    if (images.get(indexOf)!=null){
                        images.remove(indexOf);
                    }
                    images.add(indexOf, mTmpFile);
                    for (int i = 0; i < images.size(); i++) {

                        File file = images.get(indexOf);
                  /*  ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    getBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                    byte[] bytes=baos.toByteArray();*/
                        Glide.with(this).load(file).into(imageViews.get(indexOf));

                    }
                }
                break;
            case REQUEST_ALBUM_OK:
                //相册返回结果
                if (data == null) {
                    return;
                }
                Log.d(TAG, "onActivityResult:相册 " + data.getData().toString());
                ContentResolver resolver = getContentResolver();
                try {
                    File file = uri2File(data.getData());
                    if (images.get(indexOf)!=null){
                        images.remove(indexOf);
                    }
                    images.add(indexOf, file);
                    for (int i = 0; i < images.size(); i++) {
                        File file1 = images.get(indexOf);
                        Glide.with(this).load(file1).into(imageViews.get(indexOf));

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
        }

    }

    private File uri2File(Uri uri) {
        File file = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = managedQuery(uri, proj, null,
                null, null);
        int actual_image_column_index = actualimagecursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        actualimagecursor.moveToFirst();
        String img_path = actualimagecursor
                .getString(actual_image_column_index);
        file = new File(img_path);
        return file;
    }

    public int indexOf;

    @OnClick({R.id.select_iv_idcardposition, R.id.select_arrmedphoto,
            R.id.select_iv_idcardback, R.id.home_call_police,
            R.id.select_iv_carinfo, R.id.home_insurance,
            R.id.bottom
    })
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.select_iv_idcardposition:
                showChooseDialog();
                indexOf = imageViews.indexOf(view);
                break;
            case R.id.select_arrmedphoto:
                showChooseDialog();
                indexOf = imageViews.indexOf(view);
                break;
            case R.id.select_iv_idcardback:
                showChooseDialog();
                indexOf = imageViews.indexOf(view);
                break;
            case R.id.home_call_police:
                showChooseDialog();
                indexOf = imageViews.indexOf(view);
                break;
            case R.id.select_iv_carinfo:
                showChooseDialog();
                indexOf = imageViews.indexOf(view);
                break;
            case R.id.home_insurance:
                showChooseDialog();
                indexOf = imageViews.indexOf(view);
                break;
            case R.id.bottom:
                PeopleInfomation peopleInfomation = new PeopleInfomation();
                    peopleInfomation.files=images;

                Intent intent = new Intent(this, CarInfoActivity.class);
                intent.putExtra("people", peopleInfomation);
                startActivity(intent);
                break;
        }

    }


    public void showChooseDialog() {
        final String[] datas = new String[]{"打开相机", "打开相册"};
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);  //先得到构造器
        builder.setTitle("选择照片方式"); //设置标题
        //builder.setMessage("是否确认退出?"); //设置内容
        builder.setIcon(R.mipmap.ic_launcher);//设置图标，图片id即可
        //设置列表显示，注意设置了列表显示就不要设置builder.setMessage()了，否则列表不起作用。
        builder.setItems(datas, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (which == 0) {
                    showCamera();
                } else {
                    showCaptrue();
                }
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();
                Toast.makeText(MainActivity.this, "确定", Toast.LENGTH_SHORT).show();
            }
        });
        builder.create().show();
    }

    private class MyAdapter extends BaseAdapter {

        private List<Drawable> items;

        public MyAdapter(List<Drawable> items) {
            this.items = items;
        }

        public void setData(List<Drawable> items) {
            this.items = items;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public Drawable getItem(int position) {
            return items.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
                imageView = new ImageView(MainActivity.this);
                AbsListView.LayoutParams params = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                imageView.setLayoutParams(params);
                imageView.setBackgroundColor(Color.parseColor("#88888888"));
            } else {
                imageView = (ImageView) convertView;
            }
            return imageView;
        }
    }
}
